//
//  SISSUploadImageView.m
//  SISSAPP
//
//  Created by 袁应荣 on 2019/7/2.
//  Copyright © 2019 优房网. All rights reserved.
//

#import "SISSUploadImageView.h"
#import "SISSUploadImageCollectionViewCell.h"
#import "TZImagePickerController.h"
#import "SISSPhotoBrowser.h"

#import "YYRPickPhotoTool.h"


@interface SISSUploadImageView ()<UICollectionViewDelegate,UICollectionViewDataSource,MWPhotoBrowserDelegate,SISSUploadImageCollectionViewCellDelegate>

@property (weak, nonatomic) UILabel *titlelabel;
@property (weak, nonatomic) UILabel *imgNumlabel;
@property (weak, nonatomic) UICollectionView *collectionView;

/// 选中资源素材数组，用于定位已经选择的照片
@property (nonatomic, strong) NSMutableArray *selectedAssets;
@property (nonatomic, strong) NSMutableArray *tempImageArray;
@property (nonatomic, strong) UIImage *addImage;

@property (nonatomic, copy) void(^deleteHandler)(NSUInteger index);

@end
@implementation SISSUploadImageView

- (void)setIsHiddenTitle:(BOOL)isHiddenTitle {
    _isHiddenTitle = isHiddenTitle;
    self.titlelabel.hidden = self.isHiddenTitle;
    self.imgNumlabel.hidden = self.isHiddenTitle;
    if (isHiddenTitle) {
        WeakSelf
        [self.collectionView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(weakSelf).offset(2 * globelMargin);
            make.left.right.equalTo(weakSelf);
            make.height.mas_equalTo(SCREEN_WIDTH / 3);
            make.bottom.equalTo(weakSelf).offset(-2 * globelMargin);
        }];
    }
}

- (void)setTitleStr:(NSString *)titleStr {
    _titleStr = titleStr;
    if ([[titleStr substringToIndex:1] isEqualToString:@"*"]) {
        NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:titleStr];
        [attributedStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,1)];
        self.titlelabel.attributedText = attributedStr;
    } else {
        self.titlelabel.text = titleStr;
    }
}

- (void)setTag:(NSInteger)tag {
    [super setTag:tag];
    self.collectionView.tag = tag;
}

- (void)setImageUrlArr:(NSMutableArray *)imageUrlArr {
    _imageUrlArr = imageUrlArr;
    [self.tempImageArray removeAllObjects];
    [self.tempImageArray addObjectsFromArray:imageUrlArr];
    [self.tempImageArray addObject:self.addImage];
    
    self.imgNumlabel.text = [NSString stringWithFormat:@"%zd/9",self.tempImageArray.count-1];
    
    [self updateCollectionViewConstraint];
}

#pragma mark - UICollectionViewDataSource & UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.tempImageArray.count > 9 ? 9 : self.tempImageArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    SISSUploadImageCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:uploadImageCollectionViewCellReuseID forIndexPath:indexPath];

    if ([self.tempImageArray[indexPath.item] isKindOfClass:[UIImage class]]) {
        cell.isShowDeleteButton = self.tempImageArray.count-1 != indexPath.item;
        cell.image = self.tempImageArray[indexPath.item];
    } else {
        cell.isShowDeleteButton = NO;
        cell.imageUrl = self.tempImageArray[indexPath.item];
    }
    
    cell.delegate = self;
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if ((self.images.count > 0 || self.imageUrlArr.count > 0) && indexPath.item != self.tempImageArray.count-1) {
        MWPhotoBrowser *photoBrowser = [[MWPhotoBrowser alloc] initWithDelegate:self];
        [photoBrowser setCurrentPhotoIndex:indexPath.item];
        //    [photoBrowser showNextPhotoAnimated:YES];
        //    [photoBrowser showPreviousPhotoAnimated:YES];
        SISSNavigationController *navigationController = [[SISSNavigationController alloc] initWithRootViewController:photoBrowser];
        navigationController.modalPresentationStyle = UIModalPresentationFullScreen;
        [[self getCurrentViewController] presentViewController:navigationController animated:YES completion:nil];
    } else {
        WeakSelf
        
        [YYRPickPhotoTool showPickPhotoToolWithViewController:[self getCurrentViewController] maxPhotoCount:9-self.imageUrlArr.count choosePhotoHandler:^(NSMutableArray<UIImage *> * _Nonnull selectedImages, NSMutableArray<PHAsset *> * _Nonnull selectedAccest) {
            
            for (NSInteger i = 0; i < weakSelf.images.count + 1; i++) {
                [weakSelf.tempImageArray removeObjectAtIndex:weakSelf.imageUrlArr.count];
            }
            
            for (UIImage *image in selectedImages) {
                [weakSelf.tempImageArray addObject:image];
            }
            weakSelf.images = [NSMutableArray arrayWithArray:selectedImages.copy];
            [weakSelf.tempImageArray addObject:weakSelf.addImage];
            [weakSelf updateCollectionViewConstraint];
            if ([self.delegate respondsToSelector:@selector(handlePhotoFinishedAction)]) {
                [self.delegate handlePhotoFinishedAction];
            }
            
        } takePhotoHandler:^(NSMutableArray<UIImage *> * _Nonnull selectedImages, NSMutableArray<PHAsset *> * _Nonnull selectedAccest) {
            
            for (NSInteger i = 0; i < weakSelf.images.count + 1; i++) {
                [weakSelf.tempImageArray removeObjectAtIndex:weakSelf.imageUrlArr.count];
            }
            for (UIImage *image in selectedImages) {
                [weakSelf.tempImageArray addObject:image];
            }
            weakSelf.images = [NSMutableArray arrayWithArray:selectedImages.copy];
            [weakSelf.tempImageArray addObject:weakSelf.addImage];
            [weakSelf updateCollectionViewConstraint];
            if ([self.delegate respondsToSelector:@selector(handlePhotoFinishedAction)]) {
                [self.delegate handlePhotoFinishedAction];
            }
        } deleteImage:^(void (^ _Nonnull deleteHandler)(NSUInteger)) {
            
            weakSelf.deleteHandler =  deleteHandler;
        } tag:collectionView.tag];
    }
    
}


#pragma mark -- SISSUploadImageCollectionViewCellDelegate
- (void)deleteButtonClickAcionWithCell:(SISSUploadImageCollectionViewCell *)cell {
    NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
    if ([self.tempImageArray[indexPath.item] isKindOfClass:[UIImage class]]) {
        [self.images removeObjectAtIndex:indexPath.item - self.imageUrlArr.count];
        self.deleteHandler(indexPath.item - self.imageUrlArr.count);
//        [self.selectedAssets removeObjectAtIndex:indexPath.item - self.imageUrlArr.count];
    } else {
        [self.imageUrlArr removeObjectAtIndex:indexPath.item];
    }
    [self.tempImageArray removeObjectAtIndex:indexPath.item];
    
    [self updateCollectionViewConstraint];
    if ([self.delegate respondsToSelector:@selector(handlePhotoFinishedAction)]) {
        [self.delegate handlePhotoFinishedAction];
    }
}

#pragma mark -- MWPhotoBrowserDelegate
- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return self.tempImageArray.count-1;
}

- (id<MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    
    //创建图片模型
    //    MWPhoto *photo = [MWPhoto photoWithURL:[NSURL URLWithString:self.images[index]]];
    MWPhoto *photo;
    if ([self.tempImageArray[index] isKindOfClass:[UIImage class]]) {
        photo = [MWPhoto photoWithImage:self.tempImageArray[index]];
    } else {
        photo = [MWPhoto photoWithURL:[NSURL URLWithString:self.tempImageArray[index]]];
    }
    
    return photo;
}

#pragma mark - 更新collectionView约束
- (void)updateCollectionViewConstraint {
    self.imgNumlabel.text = [NSString stringWithFormat:@"%zd/9",self.tempImageArray.count-1];
    CGFloat height = self.tempImageArray.count < 4 ? SCREEN_WIDTH / 3 : (self.tempImageArray.count < 7 ? 2 * SCREEN_WIDTH / 3 : SCREEN_WIDTH);
//    CGFloat height;
//    if (self.tempImageArray.count % 3 == 0) {
//        height = (self.tempImageArray.count / 3) * SCREEN_WIDTH / 3;
//    } else {
//        height = ((self.tempImageArray.count / 3) + 1) * SCREEN_WIDTH / 3;
//    }
    
    [self.collectionView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(height);
    }];
    [self.collectionView reloadData];
}

#pragma mark - 懒加载
- (NSMutableArray *)tempImageArray {
    
    if (!_tempImageArray) {
        
        _tempImageArray = [NSMutableArray arrayWithObjects:self.addImage, nil];
    }
    return _tempImageArray;
}

- (UIImage *)addImage {
    
    if (!_addImage) {
        _addImage = [UIImage imageNamed:@"add"];
    }
    return _addImage;
}

#pragma mark - UI
- (void)initUI {
    [super initUI];
    
    self.backgroundColor = [UIColor whiteColor];
    
    UILabel *titlelabel = [UILabel yyr_labelWithText:@"合同信息" fontSize:15 textColor:MAIN_TEXT_COLOR];
    titlelabel.hidden = self.isHiddenTitle;
    [self addSubview:titlelabel];
    self.titlelabel = titlelabel;
    
    UILabel *imgNumlabel = [UILabel yyr_labelWithText:@"0/9" fontSize:15 textColor:SECONDARY_TEXT_COLOR];
    imgNumlabel.textAlignment = NSTextAlignmentRight;
    imgNumlabel.hidden = self.isHiddenTitle;
    [self addSubview:imgNumlabel];
    self.imgNumlabel = imgNumlabel;
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.minimumLineSpacing = 10;
    flowLayout.minimumInteritemSpacing = 10;
    CGFloat itemW = (SCREEN_WIDTH - 3 * 20) / 3;
    flowLayout.itemSize = CGSizeMake(itemW, itemW);
    //    flowLayout.itemSize = CGSizeMake(65, 65);
    flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
    collectionView.backgroundColor = [UIColor whiteColor];
    collectionView.dataSource = self;
    collectionView.delegate = self;
    [collectionView registerClass:[SISSUploadImageCollectionViewCell class] forCellWithReuseIdentifier:uploadImageCollectionViewCellReuseID];
    [self addSubview:collectionView];
    self.collectionView = collectionView;
}

#pragma mark - 约束
- (void)initConstraint {
    [super initConstraint];
    
    WeakSelf
    [self.titlelabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.equalTo(weakSelf).offset(2 * globelMargin);
    }];
    
    [self.imgNumlabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(weakSelf.titlelabel);
        make.right.equalTo(weakSelf.mas_right).offset(-3 * globelMargin);
    }];
    
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        if (weakSelf.isHiddenTitle) {
            make.top.equalTo(weakSelf).offset(2 * globelMargin);
        } else {
            make.top.equalTo(weakSelf.titlelabel.mas_bottom).offset(2 * globelMargin);
        }
        make.left.right.equalTo(weakSelf);
        make.height.mas_equalTo(SCREEN_WIDTH / 3);
        make.bottom.equalTo(weakSelf).offset(-2 * globelMargin);
    }];

}

@end
